package pers.llc.css.lock.unreentrant;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 通过自旋锁模拟一个不可重入锁
 *
 * @author lls
 * @time 2019/4/7 0007 15:34
 */
public class ReentrantSpinLock {

    private AtomicReference<Thread> cas = new AtomicReference<>();
    private int count;

    public void lock() {
        Thread current = Thread.currentThread();
        if (current == cas.get()) {
            count++;
            return;
        }
        while (!cas.compareAndSet(null, current)) {

        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        if (current == cas.get()) {
            if (count > 0) {
                count--;
            } else {
                cas.compareAndSet(current, null);
            }
        }
    }

}
